/* eslint-disable @typescript-eslint/camelcase */
/* eslint-disable max-len */
/* eslint-disable no-shadow */
/* eslint-disable @typescript-eslint/no-unused-vars */
/**
 * Created by zhangsong on 2019/9/22.
 */
import { routerRedux } from 'dva/router';
import { formatMessage } from '@/utils/i18n';
import ContractorReducer from '@/dva/application/contractor';
import * as contractorApi from '@/services/application/contractor';
import * as temopraryApi from '@/services/application/temoprary';
import Modal from '@/components/Modal';
import { ContractorApplication } from '@/constants/routes';
import { defaultPaginationParam } from '@/constants/styleConfig';
import globalConfig from '@/constants/config';
import URI from '@/services/uri';
import _ from 'lodash';

const urly = URI.application;

const { Namespace, State, Reducers, Effects } = ContractorReducer;

const Model = {
  namespace: Namespace,
  state: State,
  reducers: {
    [Reducers.setState](state, { data = {} } = {}) {
      return {
        ...state,
        ...data,
      };
    },
  },
  effects: {
    // 下拉的操作处理
    *[Effects.modifycontralist]({ data }, { put, call }) {
      const response = yield call(temopraryApi.modifycontractorSelete, data);
      if (response.code === 200) {
        yield put({
          type: Effects.getMainContractor,
        });
      }
    },

    *[Effects.deletecontralist]({ data }, { put, call }) {
      const response = yield call(temopraryApi.deletecontractorSelete, data);
      if (response.code === 200) {
        yield put({
          type: Effects.getMainContractor,
        });
      }
    },

    // 下拉的操作处理
    *[Effects.modifygrouplist]({ data }, { put, call }) {
      const response = yield call(temopraryApi.modifygroupSelete, data);
      if (response.code === 200) {
        yield put({
          type: Effects.getGroupList,
        });
      }
    },

    *[Effects.deletegrouplist]({ data }, { put, call }) {
      const response = yield call(temopraryApi.deletegroupSelete, data);
      if (response.code === 200) {
        yield put({
          type: Effects.getGroupList,
        });
      }
    },

    *[Effects.getDefaultData]({ data }, { put, call }) {
      const responsedef = yield call(contractorApi.getDefaultData, data);
      const checked_specified = Array.isArray(responsedef.zone_list) ? responsedef.zone_list.map(i => i.id) : []
      responsedef.checked_specified = checked_specified;
      console.log('自動填充的數據格式', responsedef, checked_specified)
      yield put({
        type: Reducers.setState,
        data: {
          defaultData: responsedef,
        },
      });
    },

    *[Effects.listSubcontractor](_, { put, call }) {
      const response = yield call(contractorApi.listSubcontractor);
      yield put({
        type: Reducers.setState,
        data: {
          subcontractor: response,
        },
      });
    },
    *[Effects.approval]({ data = {} }, { put, call }) {
      yield call(contractorApi.approval, data.id);
      yield Modal.tips(formatMessage('baseInfo.operatorSuccess'));
      yield put({
        type: Effects.getContractorById,
        data: data.id,
      });
    },
    *[Effects.disapproval]({ data }, { put, call }) {
      yield call(contractorApi.disapproval, data.id);
      yield Modal.tips(formatMessage('baseInfo.operatorSuccess'));
      yield put({
        type: Effects.getContractorById,
        data: data.id,
      });
    },

    *[Effects.reviewok]({ data }, { put, call }) {
      yield call(contractorApi.reviewok, data.id);
      yield Modal.tips(formatMessage('baseInfo.operatorSuccess'));
      yield put({
        type: Effects.getContractorById,
        data: data.id,
      });
    },

    *[Effects.saveContractor]({ data }, { put, call }) {
      yield put({
        type: Reducers.setState,
        data: {
          saveLoading: true,
        },
      });
      try {
        const response = yield call(contractorApi.saveContractor, data);
        if (response.code !== 200) {
          Modal.error({
            title: formatMessage('baseInfo.errorTitle'),
            content: _.get(response, 'blackMsg', response.msg),
          });
          yield put({
            type: Reducers.setState,
            data: {
              saveLoading: false,
              saveSuccessModal: false,
              pdfReview: [],
            },
          });
        } else {
          yield put({
            type: Reducers.setState,
            data: {
              saveLoading: false,
              saveSuccessModal: true,
              pdfReview: [],
            },
          });
        }
      } catch (e) {
        yield put({
          type: Reducers.setState,
          data: {
            saveLoading: false,
          },
        });
        Modal.error({
          title: formatMessage('baseInfo.errorTitle'),
          content: e.message,
        });
      }
    },
    *[Effects.getPreviewPdfById]({ data }, { put, call }) {
      yield put({
        type: Reducers.setState,
        data: {
          pdfLoading: true,
          pdfPreviewVisible: true,
        },
      });
      const response = yield call(contractorApi.getPDFById, data.id);
      yield put({
        type: Reducers.setState,
        data: {
          pdfLoading: false,
          pdfReview: response.map(item => `${globalConfig.host}${globalConfig.baseAPI}${item}`),
        },
      });
    },
    *[Effects.handPDFModalCancel](_, { put }) {
      yield put({
        type: Reducers.setState,
        data: {
          pdfPreviewVisible: false,
          pdfReview: [],
        },
      });
    },
    *[Effects.downLoadXlsx](_, { put, call }) {
      yield put({
        type: Reducers.setState,
        data: {
          xslloading: true,
        },
      });
      const response = yield call(contractorApi.contractorDownXlsx);
      console.log('进来了', response);
      // if (response) {
      //   const url = window.URL.createObjectURL(new Blob([response]));
      const link = document.createElement('a'); // 创建a标签
      //   link.style.display = 'none';
      link.href = urly.contractorUrl.downxlsx; // 设置a标签路径
      link.download = 'download.xlsx'; // 设置文件名， 也可以这种写法 （link.setAttribute('download', '名单列表.xls');
      document.body.appendChild(link);
      link.click();
      URL.revokeObjectURL(link.href); // 释放 URL对象
      document.body.removeChild(link);
      yield put({
        type: Reducers.setState,
        data: {
          xslloading: false,
        },
      });
    },
    *[Effects.listByParam]({ data = {} }, { put, call }) {
      const {
        page = defaultPaginationParam.page,
        pageSize = defaultPaginationParam.pageSize,
        query = {},
      } = data;
      yield put({
        type: Reducers.setState,
        data: {
          listLoading: true,
        },
      });
      try {
        const response = yield call(contractorApi.listByParam, {
          page,
          pageSize,
          ...query,
        });
        yield put({
          type: Reducers.setState,
          data: {
            listLoading: false,
            listData: response.data,
            query,
            page: response.page,
            pageSize: response.pageSize,
            total: response.total,
          },
        });
      } catch (e) {
        yield Modal.error({
          title: formatMessage('baseInfo.errorTitle'),
          content: JSON.stringify(formatMessage('applicationCommon.workerCard.errorcontext')),
        });
      }
    },
    *[Effects.removeById]({ data }, { put, call }) {
      const { page, pageSize, query, id } = data;
      yield put({
        type: Reducers.setState,
        data: {
          listLoading: true,
        },
      });
      try {
        yield call(contractorApi.removeById, id);
        yield Modal.success({
          title: formatMessage('baseInfo.removeSuccess'),
        });
      } catch (e) {
        yield Modal.error({
          title: formatMessage('baseInfo.errorTitle'),
          content: JSON.stringify(formatMessage('applicationCommon.workerCard.errorcontext')),
        });
      }
      yield put({
        type: Effects.listByParam,
        data: {
          page,
          pageSize,
          query,
        },
      });
    },
    *[Effects.getContractorById]({ data }, { put, call }) {
      yield put({
        type: Reducers.setState,
        data: {
          detailLoading: true,
          contractorInfo: {},
        },
      });
      try {
        const response = yield call(contractorApi.getById, data);
        yield put({
          type: Reducers.setState,
          data: {
            detailLoading: false,
            contractorInfo: response,
          },
        });
        if (response && response.contract_number) {
          yield put({
            type: Effects.getDefaultData,
            data: response.contract_number,
          });
        }
      } catch (e) {
        yield Modal.error({
          title: formatMessage('baseInfo.errorTitle'),
          content: JSON.stringify(formatMessage('applicationCommon.workerCard.errorcontext')),
        });
        yield put(routerRedux.push(ContractorApplication.list.url));
      }
    },
    // 註銷彈窗
    *[Effects.openCallModal]({ data }, { put, call }) {
      yield put({
        type: Reducers.setState,
        data: {
          callMadal: data,
        },
      });
    },
    // 修改group list
    *[Effects.setList]({ data }, { put, call }) {
      yield put({
        type: Reducers.setState,
        data: {
          callMadal: data,
        },
      });
    },
    // 更新註銷過期時間
    *[Effects.updateCallDate]({ data }, { put, call }) {
      yield put({
        type: Reducers.setState,
        data: {
          saveLoading: true,
        },
      });
      try {
        const response = yield call(contractorApi.updateCallDate, data.update);
        if (response.code === 200) {
          yield put({
            type: Reducers.setState,
            data: {
              callMadal: false,
            },
          });
          yield Modal.success({
            title: formatMessage('baseInfo.saveSuccess'),
            content: '',
          });
          yield put({
            type: Effects.listByParam,
            data: data.pagesize,
          });
        }
        console.log('更新看看成功不', response)
      } catch (e) {
        yield Modal.error({
          title: formatMessage('baseInfo.errorTitle'),
          content: '失敗',
        });
        yield put({
          type: Reducers.setState,
          data: {
            saveLoading: false,
          },
        });
      }
    },
    // 获取分组列表
    *[Effects.getGroupList](_, { put, call }) {
      yield put({
        type: Reducers.setState,
        data: {
          saveLoading: true,
        },
      });
      try {
        const response = yield call(contractorApi.getGroupList);
        const list = response.listNames.map(i => ({ value: i.name, label: i.name }))
        yield put({
          type: Reducers.setState,
          data: {
            saveLoading: false,
            groupList: list,
          },
        });
      } catch (e) {
        console.log('分组数据', e)
        // yield Modal.error({
        //   title: formatMessage('baseInfo.errorTitle'),
        //   content: '失敗',
        // });
        yield put({
          type: Reducers.setState,
          data: {
            saveLoading: false,
          },
        });
      }
    },
    // 修改分组列表
    *[Effects.creatGroupList]({ data }, { put, call }) {
      yield put({
        type: Reducers.setState,
        data: {
          saveLoading: true,
        },
      });
      try {
        const response = yield call(contractorApi.creatGroupList, data.data);
        console.log('新增分组数据11', response)
        const list = response.listNames.map(i => ({ value: i.label, label: i.label }))
        yield put({
          type: Reducers.setState,
          data: {
            saveLoading: false,
            groupList: list,
          },
        });
        yield put({
          type: Effects.getGroupList,
        });
      } catch (e) {
        yield Modal.error({
          title: formatMessage('baseInfo.errorTitle'),
          content: '失敗',
        });
        yield put({
          type: Reducers.setState,
          data: {
            saveLoading: false,
          },
        });
      }
    },
    // 获取主合同編號
    *[Effects.getMainContractor](_, { put, call }) {
      console.log('獲取的是主合同列表');
      yield put({
        type: Reducers.setState,
        data: {
          saveLoading: true,
        },
      });
      try {
        const response = yield call(contractorApi.getMainContractor);
        console.log('獲取的是主合同列表', response);
        const list = response.data.map(i => ({
          value: i.id, label: i.contract_number,
        }))
        yield put({
          type: Reducers.setState,
          data: {
            saveLoading: false,
            mainContractorList: list,
          },
        });
      } catch (e) {
        console.log('獲取的是主合同列表失敗', e)
        yield put({
          type: Reducers.setState,
          data: {
            saveLoading: false,
          },
        });
      }
    },
    // 修改主合同編號
    *[Effects.createMainContractor]({ data }, { put, call }) {
      yield put({
        type: Reducers.setState,
        data: {
          saveLoading: true,
        },
      });
      try {
        const response = yield call(contractorApi.createMainContractor, data);
        console.log('修改成功了', response);
        const list = response.data.map(i => ({
          value: i.id, label: i.contract_number,
        }))
        yield put({
          type: Reducers.setState,
          data: {
            saveLoading: false,
            mainContractorList: list,
          },
        });
      } catch (e) {
        console.log('修改主合同列表失敗', e)
        yield put({
          type: Reducers.setState,
          data: {
            saveLoading: false,
          },
        });
      }
    },
    *[Effects.modifyContractorById]({ data }, { put, call }) {
      const { body, id = {} } = data;
      console.log('为什么，', data)
      yield put({
        type: Reducers.setState,
        data: {
          saveLoading: true,
        },
      });
      try {
        const response = yield call(contractorApi.updateById, {
          id,
          body,
        });
        if (response.code === 200) {
          yield put({
            type: Reducers.setState,
            data: {
              saveLoading: false,
              saveSuccessModal: true,
              pdfReview: [],
            },
          });
        } else {
          yield put({
            type: Reducers.setState,
            data: {
              saveLoading: false,
            },
          });
          yield Modal.error({
            title: formatMessage('baseInfo.errorTitle'),
            content: JSON.stringify(response.msg),
          });
        }
      } catch (e) {
        console.log('为什么errrr，', e)
        yield Modal.error({
          title: formatMessage('baseInfo.errorTitle'),
          content: JSON.stringify(formatMessage('applicationCommon.workerCard.errorcontext')),
        });
        yield put({
          type: Reducers.setState,
          data: {
            saveLoading: false,
          },
        });
      }
    },
    *[Effects.sendEmail]({ data }, { put, call }) {
      yield put({
        type: Reducers.setState,
        data: {
          detailLoading: true,
        },
      });
      try {
        const response = yield call(contractorApi.sendEmail, data);
        console.log('發送郵件的信息', response)
        if (response.code === 200) {
          yield Modal.success({
            title: formatMessage('baseInfo.sendsuccess'),
            content: '',
          });
        } else {
          yield Modal.error({
            title: formatMessage('baseInfo.senderror'),
            // content: JSON.stringify(response.msg),
          });
        }
        yield put({
          type: Reducers.setState,
          data: {
            detailLoading: false,
          },
        });
      } catch (e) {
        yield Modal.error({
          title: formatMessage('baseInfo.senderror'),
          // content: JSON.stringify(formatMessage('applicationCommon.workerCard.errorcontext')),
        });
        yield put({
          type: Reducers.setState,
          data: {
            detailLoading: false,
          },
        });
      }
    },
  },
};

export default Model;
